import React, {lazy} from 'react'

import { Route } from 'react-router-dom'

import { TabBar } from 'antd-mobile'

//导入组件样式
import './index.css'

import Index from '../Index'
// import HomeList from '../HouseList'
// import News from '../News'
// import Profile from '../Profile'

const HomeList = lazy(()=>import('../HouseList')) 
const News = lazy(()=>import('../News')) 
const Profile = lazy(()=>import('../Profile'))


//TabBar数据
const tabItems = [
  {
    title: '首页',
    icon: 'icon-ind',
    path: '/home'
  },
  {
    title: '找房',
    icon: 'icon-findHouse',
    path: '/home/list'
  },
  {
    title: '资讯',
    icon: 'icon-infom',
    path: '/home/news'
  },
  {
    title: '我的',
    icon: 'icon-my',
    path: '/home/profile'
  },
]

/*
  点击首页导航菜单,导航到找房列表页面时,找房菜单没有高亮

  原来我们实现该功能时只考虑了点击以及第一次加载Home组件的情况,但是没有考虑不重新加载Home组件的路由切换

  解决
    在路由切换时也执行路由高亮的逻辑代码
      1.添加componentUpdate钩子函数
      2.在钩子函数中判断路由是否切换(因为路由的信息是通过props传递给组建的所以比较路由更新前后的2个props)
      3.路由地址切换时让菜单高亮
*/

export default class Home extends React.Component {
    state = {
        //默认选中的Tab菜单的
        selectedTab: this.props.location.pathname
    }
    //渲染TabBar的方法
    renderTabBarItem(){
      return tabItems.map(item => <TabBar.Item
        title={item.title}
        key={item.title}
        icon={<i className={ `iconfont ${item.icon}` }/>}
        selectedIcon={<i className={ `iconfont ${item.icon}` }/>}
        selected={this.state.selectedTab === item.path}
        onPress={() => {
            this.setState({
            selectedTab: item.path,
            })
            //路由切换
            this.props.history.push(item.path)
        }}
        >
        </TabBar.Item>)
    }
    componentDidUpdate(prevProps){
      if(prevProps.location.pathname!==this.props.location.pathname){
        //此时就说明路由发生切换了
        this.setState({
          selectedTab: this.props.location.pathname
        })
      }
    }
    render() {
      // console.log(this.props.location.pathname);
        return ( 
            <div className="home">
                { /* 渲染子路由 */ } 
                <Route exact path = "/home" component = { Index }></Route>
                <Route path = "/home/list" component = { HomeList }></Route>
                <Route path = "/home/news" component = { News }></Route>
                <Route path = "/home/profile" component = { Profile }></Route>
                { /* TabBar */ }
                <div className="tabbar">
                  <TabBar
                      tintColor="#21b97a"
                      barTintColor="white"
                      noRenderContent={ true }
                  >
                    {this.renderTabBarItem()}
                  </TabBar>
                </div>
            </div>
        )
    }
}